package com.example.coolshark.controller;

import com.example.coolshark.mapper.UserMapper;
import com.example.coolshark.pojo.dto.UserDto;
import com.example.coolshark.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Name: UserController
 * @Author: 西风残叶
 * @Company: 朝兮网络工作室
 * @Data: 2023/11/20 23:22
 */
@RestController
public class UserController {
    @Autowired
    UserMapper mapper;
    @RequestMapping("/login")
    public int login(@RequestBody UserDto user , HttpSession session, HttpServletResponse response){
        System.out.println("user = " + user );
        UserVO u = mapper.selectByUsername(user.getUsername());
        if (u!=null){
            if (user.getPassword().equals(u.getPassword())){
                // 把登录成功的用户对象保存在会话对象中
                session.setAttribute("user",u);
                // 判断是否需要记住密码
                if (user.getRem()){
                    // 创建 Cookie保存用户名和密码
                    Cookie username = new Cookie("username", user.getUsername());
                    Cookie password = new Cookie("password", user.getPassword());
                    // 设置保存时间
                    username.setMaxAge(60*60*24*30);
                    password.setMaxAge(60*60*24*30);
                    // 把Cookie下发给客户端
                    response.addCookie(username);
                    response.addCookie(password);
                }
                return 1;
            }else {
                return 2;
            }
        }
        return 3;
    }

    /**
     * 管理页面欢迎某某回来
     *
     * @param session :会话对象
     * @return {@link UserVO}
     */
    @RequestMapping("/cur9rentUser")
    public UserVO  currentUser(HttpSession session){
        return (UserVO) session.getAttribute("user");
    }

    /**
     * 退出登录
     * @param session
     */
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        // 删除会话对象
        session.removeAttribute("user");
    }
}
